using System;
using System.Linq;
using TestCases.Utils.Comparers;

namespace TestCases.CompareAssert.Core.Selectors
{
    public class CompatibleInterfacesSelector: ITypeSelector
    {
        private readonly string _interfaceName;

        public CompatibleInterfacesSelector(string interfaceName)
        {
            if (interfaceName.LastIndexOf('`') < 0)
            {
                throw new ArgumentException("Interface name must be a generic type name with '`' suffix", "interfaceName");
            }            
            _interfaceName = interfaceName;
        }

        public Type[] SelectFrom(Type leftType, Type rightType)
        {

            var filtered = from leftInterface in leftType.GetInterfaces()
                              from rightInterface in rightType.GetInterfaces()
                              where leftInterface.Name == _interfaceName && leftInterface == rightInterface
                              select leftInterface;

            var result = filtered.OrderByDescending(x => x.GetGenericArguments(), 
                new EnumerableComparer<Type>(TypeComparer.Instance)).ToArray();                
            return result;
        }
    }
}